package alijk.dataView.utils;

import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.AndFilter;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 中关村笑话抓取
 * 2014年11月23日下午8:46:06
 * @author CheWenliang
 */
public class ZolJokeParser {
	public static final Logger logger = LoggerFactory
			.getLogger(ZolJokeParser.class);
	private static String url= "http://xiaohua.zol.com.cn/new/";
	private static final String filterClass = "summary-text";
	private static final String filterTag = "div";
	/*
	 * 单条
	 * @return
	 */
	public static String getOneJoke(){
		return getZolPageJoke(true);
	}
	/*
	 * 一页中全部的
	 */
	public static String getAllJoke(){
		
		return getZolPageJoke(false);
	}
	/**
	 * 主要逻辑方法
	 * @param isOne
	 * @return
	 */
	private static String getZolPageJoke(boolean isOne){
		String result = "";
		String pageUrl = url;
		int page = (int)(Math.random()*800+1);
		if(page != 1){
			pageUrl = pageUrl + page + ".html";
		}
		logger.info(pageUrl);
		Parser myParser;
		try {
			myParser = new Parser(pageUrl);
			// 设置编码
			myParser.setEncoding("GBK");
			//找出所有 div 里含有class="summary-text"的节点
			NodeFilter filter = new AndFilter(new NodeFilter[]{new TagNameFilter(filterTag),
					new HasAttributeFilter("class",filterClass)});
			NodeList nodeList = myParser.extractAllNodesThatMatch(filter);
			
			//如果只要一条的话，随机从20条中拿出一条
			if(isOne){
				int wicthOne = (int)(Math.random()*20+1);
				Node oneNode = nodeList.elementAt(wicthOne);
				result = oneNode.toPlainTextString();
				return result;
			}
			for (int j = 1; j < nodeList.size(); j++) {
				Node node = nodeList.elementAt(j);
				//拿出节点里所有的text
				String text = node.toPlainTextString();
				result = result + text +"\n";
			}
		} catch (ParserException e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		}
		return result;
	}
	public static void main(String[] args) {
		System.out.println(getOneJoke());
	}
}
